<?php
class System
{
	static private $_c = '';
	static private $_a = '';
	
	public static $coreClass = array(
		'DB'     		=> 'DB.php',
		'View'     		=> 'View.php',
		'Lang'     		=> 'Lang.php',	
	);
	
	static public function run()
	{
		$r = isset($_GET['r'])?$_GET['r']:'';
		unset($_REQUEST['r']);
		if (stristr($r, '/'))
		{
			list($c, $a) = explode('/', $r);
		}
		else
		{
			$c = $a = 'Index';
		}
		
		self::$_c = ucfirst($c).'Controller';
		self::$_a = ucfirst($a).'Action';
		$params = $_REQUEST;
		if (method_exists(self::$_c, self::$_a))
		{
			return call_user_func_array(array(self::$_c, self::$_a), array($params));
		}
		else
		{
			System::halt("404 NOT FOUND [{$c}::{$a}]");
		}
	}
	
	public static function autoLoad($className) 
	{	
		if (isset(System::$coreClass[$className])) 
		{			
			//当$className在核心类引导数组中存在时, 加载核心类文件			
			System::loadFile(LIB_PATH . System::$coreClass[$className]);			
		}
		else if (substr($className, -10) == 'Controller') 
		{			
			//modlel文件自动加载分析			
			if (is_file(C_DIR . $className . '.php')) 
			{				
				//当所要加载的model文件存在时
				System::loadFile(C_DIR . $className . '.php');
			} 
			else 
			{				
				//当所要加载的文件不存在时,显示错误提示信息
				System::halt('Controller文件: ' . $className . ' 不存在!');	
			}
		}
		else if (substr($className, -5) == 'Model') 
		{			
			//modlel文件自动加载分析			
			if (is_file(M_DIR . $className . '.php')) 
			{				
				//当所要加载的model文件存在时
				System::loadFile(M_DIR . $className . '.php');
			} 
			else 
			{				
				//当所要加载的文件不存在时,显示错误提示信息
				System::halt('Model文件: ' . $className . ' 不存在!');	
			}
		}
	}
	
	public static function loadFile($fileName) 
	{
		if (is_file($fileName)) 
		{
			require_once($fileName);
		}
		else
		{
			//当所要加载的文件不存在时,错误提示
			System::halt('The file:' . $fileName . ' not found!');
		}
	}
	
	public static function halt($msg)
	{
		die($msg);
	}
}

spl_autoload_register(array('System', 'autoLoad'));